package org.iabako.client.ui.form.extranet;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import org.iabako.client.config.page.PageConfigEnum;
import org.iabako.client.config.page.PageEnum;
import org.iabako.client.init.Iabako;
import org.iabako.client.navigation.NavigationController;
import org.iabako.client.tools.IabakoAsyncCallback;
import org.iabako.client.ui.form.AbstractForm;
import org.iabako.client.ui.layout.field.*;
import org.iabako.client.ui.layout.widget.validation.ValidationMessage;
import org.iabako.shared.entity.business.AbstractEntity;
import org.iabako.shared.entity.user.User;
import org.iabako.shared.iservice.security.AuthenticateServiceAsync;
import org.iabako.shared.tools.GenericTools;

import java.util.List;

/**
 * Created by jose on 28/09/14.
 */
public abstract class LoginForm extends AbstractForm {


    interface MyUiBinder extends UiBinder<HTMLPanel, LoginForm> {
    }

    protected MyUiBinder binderForm = GWT.create(MyUiBinder.class);

    private AuthenticateServiceAsync authenticateServiceAsync = AuthenticateServiceAsync.Util.getInstance();


    @UiField
    InputTextEmail email;
    @UiField
    InputTextPassword password;
    @UiField
    Button sigInButton;
    @UiField
    FormPanel signInForm;
    @UiField
    LabelText passwordReminderLink;

    public LoginForm() {
        simplePopup = true;
        setForm(binderForm, PageConfigEnum.Login, null);

        //Spring security
        email.getInputField().setName("j_username");
        password.getInputField().setName("j_password");
        //Browser auto-completion
        email.getInputField().getElement().setAttribute("autocomplete", "true");
        password.getInputField().getElement().setAttribute("autocomplete", "true");

        email.getInputField().addKeyPressHandler(new SubmitEventListener());
        password.getInputField().addKeyPressHandler(new SubmitEventListener());

        signInForm.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
            public void onSubmitComplete(FormPanel.SubmitCompleteEvent event) {
                authenticateServiceAsync.getAuthenticatedUser(new IabakoAsyncCallback<User>() {
                    public void onSuccess(User user) {
                        if (user != null) {
                            //Sign in success
                            Iabako.showHomePage();
                        } else {
                            ValidationMessage.getFirstFromDOM().showErrorMessage(true, true, "validation_sign_in_error");
                            email.addErrorMessage(email, false, "");
                            password.addErrorMessage(password, false, "");
                        }
                        super.onSuccess(user);
                    }
                });
            }
        });

        passwordReminderLink.getLabel().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                NavigationController.getInstance().closePopups();
                NavigationController.getInstance().goTo(PageEnum.PasswordReminder);
            }
        });

        sigInButton.getButton().addClickHandler(new SubmitEventListener());
    }

    @Override
    protected List<IField> getMandatoryFields() {
        return null;
    }

    @Override
    protected AbstractEntity getEntity() {
        return null;
    }

    @Override
    public boolean validate() {
        if (GenericTools.isEmpty(email.getValue()) || GenericTools.isEmpty(password.getValue())) {
            if (GenericTools.isEmpty(email.getValue())) {
                email.addErrorMessage(email, true, "validation_sign_in_empty_email_or_password_error");
            }
            if (GenericTools.isEmpty(password.getValue())) {
                password.addErrorMessage(password, true, "validation_sign_in_empty_email_or_password_error");
            }
            return false;
        }
        if (!email.isValid()) {
            email.addErrorMessage(email, true, "validation_sign_in_email_format_error");
            return false;
        }
        return true;
    }

    private class SubmitEventListener implements ClickHandler, KeyPressHandler {
        public void onClick(ClickEvent event) {
            signIn();
        }

        public void onKeyPress(KeyPressEvent event) {
            if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
                signIn();
            }
        }

        private void signIn() {
            if (validate()) {
                signInForm.submit();
            }
        }
    }
}
